package com.ychen.commons.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Encoder;

import java.util.Date;

/**
 * jwt工具类
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2017/9/21 22:21
 */
public class JwtUtils {
    private static Logger logger = LoggerFactory.getLogger(JwtUtils.class);

    private final static String token = "token";
    private final static String key = "gsdfgf32.;'..;dfs";
    private final static byte[] bt = key.getBytes();
    private final static String default_secret = (new BASE64Encoder()).encodeBuffer(bt);
    public final static Long default_expire = 3600 *24L;

    /**
     * 生成jwt token
     * @param userId
     * @param subject
     * @param expire
     * @param secret
     * @return
     */
    public static String generateToken(long userId, String subject, Long expire, String secret) {

        if (expire == null) {
            expire = default_expire;
        }
        Date nowDate = new Date();
        //过期时间
        Date expireDate = new Date(nowDate.getTime() + expire * 1000);

        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setSubject(subject)
                .setId(userId + "")
                .setIssuedAt(nowDate)
                .setExpiration(expireDate)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    /**
     * 生成jwt token
     *
     * @param userId
     * @param subject
     * @param expire  过期时间/秒
     * @return
     */
    public static String generateToken(long userId, String subject, Long expire) {
        return generateToken(userId, subject, expire, default_secret);
    }

    public static Claims getClaimByToken(String token, String secret) {
        try {
            return Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            logger.debug("validate is token error ", e);
            return null;
        }
    }

    public static Claims getClaimByToken(String token) {
        return getClaimByToken(token, default_secret);
    }

    /**
     * token是否过期
     *
     * @return true：过期
     */
    public static boolean isTokenExpired(Date expiration) {
        return expiration.before(new Date());
    }

    public static String getHeader() {
        return token;
    }

}
